package com.tms.utils.image.impl;

import cn.hutool.core.date.DateUtil;
import com.tms.utils.image.ImageService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Random;

@Service
public class ImageServiceImpl implements ImageService {

    private final String computerRootDirectory = "user.home";
    private final String projectRootDirectory = "/tms/upload";
    private final String spilt = "/";
    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 存储图片并返回相应的存储路径
     *
     * @param image      图片文件
     * @param workcellId 对应的workcell
     * @param type       bill还是scrap或者repair
     * @return
     */
    @Override
    public String getName(MultipartFile image, int workcellId, String type) {
        if (image == null) {
            return null;
        }
        String imageName = null;
        try {
            // 获取用户目录计算机当前登录的用户的根目录(C:\Users\xh)
            String userPath = System.getProperties().getProperty(computerRootDirectory) + projectRootDirectory + spilt;
            // 以workcellId以及类型（报废、修理）为目录
            StringBuffer hold = new StringBuffer(String.valueOf(workcellId) + spilt + type + spilt);
            // 获取时间，以年月创建目录
            hold.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
            File mediaPath = new File(userPath, hold.toString());
            // 如果没有该目录则创建
            if (!mediaPath.exists()) {
                mediaPath.mkdirs();
            }
            // 生成文件名称
            String nameSuffix = Objects.requireNonNull(image.getOriginalFilename()).substring(0, image.getOriginalFilename().lastIndexOf("."))
                    .replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date())
                    + new Random().nextInt(1000);
            // 文件后缀
            String fileSuffix = image.getOriginalFilename()
                    .substring(image.getOriginalFilename().lastIndexOf(".") + 1);
            // 上传文件名加后缀
            String fileName = nameSuffix + "." + fileSuffix;

            // 转存文件
            image.transferTo(new File(mediaPath.toString(), fileName));

            // 原图片路径
            StringBuffer originalPath = new StringBuffer();
            originalPath.append(mediaPath.getAbsolutePath()).append("/").append(fileName);
            // 压缩图片路径
            StringBuffer compressPath = new StringBuffer();
            compressPath.append(mediaPath.getAbsolutePath()).append("/").append(nameSuffix).append("_small.")
                    .append(fileSuffix);
            // 压缩图片
            Thumbnails.of(originalPath.toString()).size(256, 256).keepAspectRatio(true).toFile(compressPath.toString());
            // 原图数据库路径
            StringBuffer originalDataPath = new StringBuffer();
            originalDataPath.append("/").append(hold).append(fileName);
            // 压缩图数据库路径
            StringBuffer compressDataPath = new StringBuffer();
            compressDataPath.append("/").append(hold).append(nameSuffix).append("_small.").append(fileSuffix);
            imageName = compressDataPath.toString();
        } catch (Exception e) {

        }
        return projectRootDirectory.substring(4) + imageName;
    }
}
